package com.shqcjd.yunweiyanoperator.ui.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.TextInputLayout;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.shqcjd.yunweiyanoperator.R;
import com.shqcjd.yunweiyanoperator.api.ApiService;
import com.shqcjd.yunweiyanoperator.app.AppConstant;
import com.shqcjd.yunweiyanoperator.helper.rxjavahelper.RxObserver;
import com.shqcjd.yunweiyanoperator.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.yunweiyanoperator.model.ResponseData;
import com.shqcjd.yunweiyanoperator.model.eventbus.CompanyRegisterSuccessEvebt;
import com.shqcjd.yunweiyanoperator.model.eventbus.WechatLoginEvent;
import com.shqcjd.yunweiyanoperator.ui.activity.guest.GuestMainActivity;
import com.shqcjd.yunweiyanoperator.ui.activity.staff.MainActivity;
import com.shqcjd.yunweiyanoperator.model.pojo.LoginBean;
import com.shqcjd.yunweiyanoperator.ui.base.BaseActivity;
import com.shqcjd.yunweiyanoperator.ui.base.BasePresenter;
import com.shqcjd.yunweiyanoperator.util.PrefUtils;
import com.shqcjd.yunweiyanoperator.util.ToastUtils;
import com.shqcjd.yunweiyanoperator.util.encrypt.encrypt.RSAUtils;
import com.shqcjd.yunweiyanoperator.widget.LoginTipsDialog;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;

public class LoginActivity extends BaseActivity {

    @BindView(R.id.et_user_number)
    EditText etUserNumber;
    @BindView(R.id.textinput_number)
    TextInputLayout textinputNumber;
    @BindView(R.id.et_user_pwd)
    EditText etUserPwd;
    @BindView(R.id.textinput_pwd)
    TextInputLayout textinputPwd;
    @BindView(R.id.tv_login)
    TextView tvLogin;
    @BindView(R.id.tv_forget_password)
    TextView tvForgetPassword;
    @BindView(R.id.tv_register)
    TextView tvRegister;
    @BindView(R.id.tv_guest)
    TextView tv_guest;

    @BindView(R.id.tv_wechat)
    TextView tvWechat;

    private Context mContext;
    public static String wechatName = "";
    public static String wechatOpenid = "";

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_login;
    }

    @Override
    public void initView() {
        EventBus.getDefault().register(this);
        IWXAPI api = WXAPIFactory.createWXAPI(this, "wx071d628d24dc00d9", false);
        api.registerApp("wx071d628d24dc00d9");

        mContext = this;
        etUserNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                username();
            }
        });

        etUserPwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                password();
            }
        });


    }

    private boolean username() {
        if (TextUtils.isEmpty(etUserNumber.getText().toString().trim())) {
            textinputNumber.setError("手机号不能为空");
            return false;
        } else {
            textinputNumber.setError(null);
            textinputNumber.setErrorEnabled(false);

        }
        return true;
    }

    private boolean password() {
        if (TextUtils.isEmpty(etUserPwd.getText().toString().trim())) {
            textinputPwd.setError("密码不能为空");
            return false;
        } else {
            textinputPwd.setError(null);
            textinputPwd.setErrorEnabled(false);
        }
        return true;
    }


    @OnClick({R.id.tv_login, R.id.tv_forget_password, R.id.tv_register, R.id.tv_wechat,R.id.tv_guest})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_login:
                login();
                break;
            case R.id.tv_forget_password://忘记密码
                startActivity(new Intent(this, ForgetPwdActivity.class));
                break;
            case R.id.tv_register:
                Intent it = new Intent(this, PersonalRegisterActivity.class);
                it.putExtra("isWechat", false);
                startActivity(it);
                break;
            case R.id.tv_wechat:
                IWXAPI api = WXAPIFactory.createWXAPI(LoginActivity.this, null);
                api.registerApp("wx071d628d24dc00d9");
                if (!api.isWXAppInstalled()) {
                    Toast.makeText(LoginActivity.this, "您的设备未安装微信客户端", Toast.LENGTH_SHORT).show();
                } else {
                    final SendAuth.Req req = new SendAuth.Req();
                    req.scope = "snsapi_userinfo";
                    req.state = "wechat_sdk_demo_test";
                    api.sendReq(req);
                }
                break;
            case R.id.tv_guest://游客登录
                guestToLogin();
                break;
        }
    }


    private void guestToLogin() {
        ApiService.guestLogin()
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<LoginBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("加载中");
                    }
                    @Override
                    public void _onNext(ResponseData<LoginBean> retData) {
                        if (retData.retCode == 10000) {
                            PrefUtils.setString(mContext, AppConstant.TOKEN_KEY, retData.data.token);
                            PrefUtils.setString(mContext, PrefUtils.USER_NAME, retData.data.userName);
                            PrefUtils.setInt(mContext, PrefUtils.USER_TYPE, retData.data.userType);
                            startActivity(new Intent(mContext, GuestMainActivity.class));
                            finish();
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        hideWaitingDialog();
                        ToastUtils.showShort(mContext, "登录失败");
                    }

                    @Override
                    public void _onComplete() {
                        super._onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    private void login() {
        if (!username() && !password()) {
            return;
        }
        Map<String, String> map = new HashMap<>();
        map.put("phoneNumber", etUserNumber.getText().toString().trim());
        map.put("password", etUserPwd.getText().toString().trim());
        //        String encrypt = RSAUtils.encrypt(RSAUtils.PUCLIC_KEY, new JSONObject(map).toString());
        ApiService.login(new JSONObject(map).toString())
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<LoginBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("加载中");
                    }

                    @Override
                    public void _onNext(ResponseData<LoginBean> retData) {
                        if (retData.retCode == 10000) {
                            PrefUtils.setString(mContext, PrefUtils.PHONE_NUMBER, retData.data.phoneNumber);
                            PrefUtils.setString(mContext, AppConstant.TOKEN_KEY, retData.data.token);
                            PrefUtils.setString(mContext, PrefUtils.TOKEN, retData.data.token);
                            PrefUtils.setBoolean(mContext, PrefUtils.FIRST_LOGIN, true);
                            PrefUtils.setInt(mContext, PrefUtils.USER_ID, retData.data.id);
                            PrefUtils.setInt(mContext, PrefUtils.USER_GUIDE_ID, Integer.parseInt("1"+retData.data.id));//用于远程指导和信令的用户id 操作端前缀加1 专家端前缀加2
                            PrefUtils.setString(mContext, PrefUtils.USER_ACCOUNT, etUserNumber.getText().toString().trim());
                            PrefUtils.setString(mContext, PrefUtils.USER_PWD, etUserPwd.getText().toString().trim());
                            PrefUtils.setInt(mContext, PrefUtils.USER_TYPE, retData.data.userType);
                            PrefUtils.setInt(mContext, PrefUtils.USER_STATE, retData.data.status);
                            PrefUtils.setString(mContext, PrefUtils.USER_NAME, retData.data.userName);
                            PrefUtils.setString(mContext, PrefUtils.BUSINESSId, retData.data.businessId);
                            PrefUtils.setString(mContext, PrefUtils.APPCODE, retData.data.appCode);
//                            PrefUtils.setInt(mContext, PrefUtils.ORGANIZATION_TYPE, retData.data.organizationType);
                            PrefUtils.setString(mContext, PrefUtils.BUSINESSNAME, retData.data.businessName);
                            PrefUtils.setString(mContext, PrefUtils.MAINTAININFO, retData.data.maintainInfo);
                            PrefUtils.setString(mContext, PrefUtils.DEPARTMENTNAME, retData.data.departmentName);

                            String json = new Gson().toJson(retData.data);
                            PrefUtils.setString(mContext, PrefUtils.LOGIN_BEAN, json);

//                            if (retData.data.userType == 1) {
//                                //管理员用户界面
//                                startActivity(new Intent(mContext, AdministerMainActivity.class));
//                            } else if (retData.data.userType == 2) {
//                                //普通员工界面
//                                startActivity(new Intent(mContext, MainActivity.class));
//                            }
                            startActivity(new Intent(mContext, MainActivity.class));
                            finish();
                        } else if(retData != null && retData.retCode == 20009) {
                            LoginTipsDialog loginDialog = new LoginTipsDialog(mContext);
                            loginDialog.show();
                            loginDialog.setTextStr("审核未通过", "审核成功之后才能登录");
                        }else {
                            ToastUtils.showShort(mContext, retData.retMsg);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        hideWaitingDialog();
                        ToastUtils.showShort(mContext, "登录失败");
                    }

                    @Override
                    public void _onComplete() {
                        super._onComplete();
                        hideWaitingDialog();
                    }
                });
    }


    private void wechatLogin(String mWechatOpenid) {
        Map<String, String> map = new HashMap<>();
        map.put("appCode", "factory");
        map.put("openId", mWechatOpenid);
        ApiService.wechatLogin(new JSONObject(map).toString())
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<LoginBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("加载中");
                    }

                    @Override
                    public void _onNext(ResponseData<LoginBean> retData) {
                        if (retData.retCode == 10000) {
                            PrefUtils.setString(mContext, PrefUtils.PHONE_NUMBER, retData.data.phoneNumber);
                            PrefUtils.setString(mContext, AppConstant.TOKEN_KEY, retData.data.token);
                            PrefUtils.setString(mContext, PrefUtils.TOKEN, retData.data.token);
                            PrefUtils.setBoolean(mContext, PrefUtils.FIRST_LOGIN, true);
                            PrefUtils.setInt(mContext, PrefUtils.USER_ID, retData.data.id);
                            PrefUtils.setInt(mContext, PrefUtils.USER_GUIDE_ID, Integer.parseInt("1"+retData.data.id));//用于远程指导和信令的用户id 操作端前缀加1 专家端前缀加2
                            PrefUtils.setString(mContext, PrefUtils.USER_ACCOUNT, etUserNumber.getText().toString().trim());
                            PrefUtils.setString(mContext, PrefUtils.USER_PWD, etUserPwd.getText().toString().trim());
                            PrefUtils.setInt(mContext, PrefUtils.USER_TYPE, retData.data.userType);
                            PrefUtils.setInt(mContext, PrefUtils.USER_STATE, retData.data.status);
                            PrefUtils.setString(mContext, PrefUtils.USER_NAME, retData.data.userName);
                            PrefUtils.setString(mContext, PrefUtils.BUSINESSId, retData.data.businessId);
                            PrefUtils.setString(mContext, PrefUtils.APPCODE, retData.data.appCode);
//                            PrefUtils.setInt(mContext, PrefUtils.ORGANIZATION_TYPE, retData.data.organizationType);
                            PrefUtils.setString(mContext, PrefUtils.BUSINESSNAME, retData.data.businessName);
                            PrefUtils.setString(mContext, PrefUtils.MAINTAININFO, retData.data.maintainInfo);
                            PrefUtils.setString(mContext, PrefUtils.DEPARTMENTNAME, retData.data.departmentName);

                            String json = new Gson().toJson(retData.data);
                            PrefUtils.setString(mContext, PrefUtils.LOGIN_BEAN, json);

                            startActivity(new Intent(mContext, MainActivity.class));
                            finish();
                        } else if(retData != null && retData.retCode == 20009) {
                            LoginTipsDialog loginDialog = new LoginTipsDialog(mContext);
                            loginDialog.show();
                            loginDialog.setTextStr("审核未通过", "审核成功之后才能登录");
                        }
                        //如果没有注册的话  就跳转到注册页
                        else if(retData != null && retData.retCode == 20023){
                            Intent it = new Intent(mContext, PersonalRegisterActivity.class);
                            it.putExtra("isWechat", true);
                            startActivity(it);
                        }
                        else {
                            ToastUtils.showShort(mContext, retData.retMsg);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        hideWaitingDialog();
                        ToastUtils.showShort(mContext, "登录失败");
                    }

                    @Override
                    public void _onComplete() {
                        super._onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onWechatLoginEvent(WechatLoginEvent event) {
        wechatLogin(wechatOpenid);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
